
const handlePing = ()=>{ 
    console.log("ping")
}

const handleAricleSearch = (data) => {
    // console.log("article_search",data)
    const customEvent = new CustomEvent("article_search", { detail:data});
    // 注册一个自定义事件
    window.dispatchEvent(customEvent);
}

class WebSocketRequestPool {
    constructor(url) {
        this.url = url; // WebSocket 服务器地址
        this.socket = null; // 保存 WebSocket 实例
        this.isConnected = false; // 表示连接状态
        this.messageHandlers = {
            ping: handlePing,
            article_search: handleAricleSearch,
        }; // 消息处理器映射表，按消息类型存储处理器
        this.defaultHandler = null; // 默认处理器，用于未定义消息类型
        this.pingInterval = 30 * 1000; // 30秒发送一次心跳
        this.reconnectTimeout = 30 * 1000; // 超过30秒未响应自动重连
        this.lastMessageTimestamp = Date.now(); // 上次收到消息的时间戳
        this.reconnectTimer = null; // 保存重连计时器
    }

    // 建立连接
    connect() {
    return new Promise((resolve, reject) => {
        if (this.isConnected) {
            console.log("WebSocket is already connected.");
            resolve();
            return;
        }

        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            this.isConnected = true;
            this.lastMessageTimestamp = Date.now();
            this.startPing();
            this.startReconnectTimer();
            resolve();
        };

        this.socket.onerror = (error) => {
            console.error("WebSocket error:", error);
            this.isConnected = false;
            reject(error);
        };

        this.socket.onclose = () => {
            this.isConnected = false;
            this.stopPing();
            this.stopReconnectTimer();
        };

        this.socket.onmessage = (event) => {
            // console.log("Received message:", event.data);
            this.lastMessageTimestamp = Date.now();
            try {
                const message = JSON.parse(event.data);
                const type = message.type;
                const handler = this.messageHandlers[type];
                if (handler) {
                    handler(message.payload);
                } else if (this.defaultHandler) {
                    this.defaultHandler(message);
                } else {
                    // console.warn(`No handler found for message type: ${type}`);
                }
            } catch (error) {
                // console.error("Failed to process message:", error);
            }
        };
    });
}

    // 注册指定类型的消息处理器
    // 监听消息
    onMessage(type, handler) {
        // 将消息类型和对应的处理函数存储到messageHandlers对象中
        this.messageHandlers[type] = handler;
    }
    
    // 注册默认消息处理器
    onDefaultMessage(handler) {
        this.defaultHandler = handler;
    }

    // 发送消息
    sendMessage(type, payload) {
        // console.log("Sending message:", { type, payload });
        if (this.isConnected && this.socket) {
            const message = JSON.stringify({ type, payload });
            this.socket.send(message);
        } else {
            this.reconnect();
            console.error("WebSocket is not connected. Cannot send message.");
        }
    }

    // 关闭 WebSocket 连接
    disconnect() {
        if (this.socket) {
            this.socket.close();
            this.isConnected = false;
            // console.log("WebSocket connection manually closed.");
        }
    }

    // 心跳机制：定期发送 "ping" 消息
    startPing() {
        this.pingTimer = setInterval(() => {
            if (this.isConnected) {
                this.sendMessage("ping", { message: "heartbeat" });
            }
        }, this.pingInterval); // 每 30 秒发送一次心跳
    }

    stopPing() {
        if (this.pingTimer) {
            clearInterval(this.pingTimer);
            this.pingTimer = null;
        }
    }

    // 启动重连监控
    startReconnectTimer() {
        this.reconnectTimer = setInterval(() => {
            const now = Date.now();
            if (now - this.lastMessageTimestamp > this.reconnectTimeout) {
                console.warn("No message received in the last 30 seconds. Reconnecting...");
                this.reconnect(); // 执行重连
            }
        }, 5 * 1000); // 每 5 秒检查一次
    }

    stopReconnectTimer() {
        if (this.reconnectTimer) {
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
        }
    }

    // 执行重连逻辑
    reconnect() {
        this.disconnect(); // 先断开现有连接
        this.connect().then(() => {
            // console.log("Reconnected to WebSocket server.");
        }).catch((error) => {
            // console.error("Reconnection failed:", error);
        });
    }

}

export default WebSocketRequestPool;